package com.ruoyi.framework.web.service;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.exception.user.UserPasswordRetryLimitExceedException;
import com.ruoyi.common.utils.StrUtil;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.framework.security.handle.MigratingPasswordEncoder;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 登录密码方法
 *
 * @author ruoyi
 */
@Component
public class SysPasswordService {
    @Autowired
    private RedisCache redisCache;

    @Value(value = "${user.password.maxRetryCount}")
    private int maxRetryCount;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Value(value = "${user.password.lockTime}")
    private int lockTime;

    /**
     * 登录账户密码错误次数缓存键名
     *
     * @param username 用户名
     * @return 缓存键key
     */
    private String getCacheKey(String username) {
        return CacheConstants.PWD_ERR_CNT_KEY + username;
    }

    public void validate(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String username = usernamePasswordAuthenticationToken.getName();
        String password = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(username));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        if (!matches(user, password)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(username), retryCount, lockTime, TimeUnit.MINUTES);
            throw new UserPasswordNotMatchException();
        } else {
            clearLoginRecordCache(username);
        }
        upgradePasswordIfNecessary(username,password);
    }

    public void validatePhoneSms(SysUser user) {
        Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
        String phonenumber = usernamePasswordAuthenticationToken.getName();
        String smsCode = usernamePasswordAuthenticationToken.getCredentials().toString();

        Integer retryCount = redisCache.getCacheObject(getCacheKey(phonenumber));

        if (retryCount == null) {
            retryCount = 0;
        }

        if (retryCount >= Integer.valueOf(maxRetryCount).intValue()) {
            throw new UserPasswordRetryLimitExceedException(maxRetryCount, lockTime);
        }

        String code = redisCache.getCacheObject(phonenumber + "-" + Constants.SMS_TPL_TYPE_0);
        if (StrUtil.isBlank(code)) {
            throw new BadCredentialsException("没有发送验证码");
        }
        if (!StrUtil.equals(smsCode, code)) {
            retryCount = retryCount + 1;
            redisCache.setCacheObject(getCacheKey(phonenumber), retryCount, lockTime, TimeUnit.MINUTES);
            throw new BadCredentialsException("短信验证码错误");
        }

        clearLoginRecordCache(phonenumber);
        redisCache.deleteObject(phonenumber + "-" + Constants.SMS_TPL_TYPE_0);
    }

    public void upgradePasswordIfNecessary(String phonenumber, String rawPassword) {
        SysUser user = userService.selectUserByPhonenumber(phonenumber,0);
        if (user != null && passwordEncoder instanceof MigratingPasswordEncoder) {
            MigratingPasswordEncoder migratingEncoder = (MigratingPasswordEncoder) passwordEncoder;
            // 检查当前存储的密码是否是旧格式
            if (migratingEncoder.needsUpgrade(user.getPassword())) {
                // 用新算法（BCrypt）重新加密明文密码
                String newEncodedPassword = migratingEncoder.encode(rawPassword);
                user.setPassword(newEncodedPassword);
                userService.updateUser(user); // 保存新哈希
            }
        }
    }


    public boolean matches(SysUser user, String rawPassword) {
        return passwordEncoder.matches(rawPassword,user.getPassword());
    }

    public void clearLoginRecordCache(String loginName) {
        if (redisCache.hasKey(getCacheKey(loginName))) {
            redisCache.deleteObject(getCacheKey(loginName));
        }
    }
}
